<template>
  <div>
    <el-dialog
      v-if="isDialog"
      :title="titlename"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      append-to-body
      width="80%"
      @close="close"
    >

      <div class="top">
        <el-input
          v-model="kwInput"
          placeholder="输入 任意字符 进行筛选"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
        <el-button
          type="primary"
          class="el-icon-plus add-btn"
          :disabled="listLoading"
          @click="handleAction('create', '添加图片')"
        >添加图片
        </el-button>
      </div>

      <el-table
        v-loading.fullscreen.lock="listLoading"
        :data="data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSort"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column align="center" label="图片" prop="url" sortable="custom">
          <template slot-scope="scope">
            <img :src="scope.row.url" height="45px" width="45px">
          </template>
        </el-table-column>
        <el-table-column align="center" label="主图" prop="main" sortable="custom">
          <template slot-scope="scope">
            <el-button
              v-if="!scope.row.main"
              size="mini"
              type="warning"
              @click="handleSetMainImage(scope.row)"
            >设为主图
            </el-button>
            <el-tag v-else type="success">主图</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="info" @click="handleAction('edit', scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">本地删除</el-button>
            <el-button v-if="scope.row.is_local" size="mini" type="primary" @click="handleAddImageToWeb(scope.row)">
              添加到网站
            </el-button>
            <el-button
              v-if="!scope.row.is_local"
              size="mini"
              type="warning"
              @click="handleDeleteImageFromWeb(scope.row)"
            >从网站删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />

    </el-dialog>
    <div v-else>
      <div class="top">
        <el-input
          v-model="kwInput"
          placeholder="输入 任意字符 进行筛选"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
        <el-button
          type="primary"
          class="el-icon-plus add-btn"
          :disabled="listLoading"
          @click="handleAction('create', '添加图片')"
        >添加图片
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSort"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column align="center" label="图片" prop="url" sortable="custom">
          <template slot-scope="scope">
            <img :src="scope.row.url" height="45px" width="45px">
          </template>
        </el-table-column>
        <el-table-column align="center" label="主图" prop="main" sortable="custom">
          <template slot-scope="scope">
            <el-button
              v-if="!scope.row.main"
              size="mini"
              type="warning"
              @click="handleSetMainImage(scope.row)"
            >设为主图
            </el-button>
            <el-tag v-else type="success">主图</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="info" @click="handleAction('edit', scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">本地删除</el-button>
            <el-button v-if="scope.row.is_local" size="mini" type="primary" @click="handleAddImageToWeb(scope.row)">
              添加到网站scope.row.is_local
            </el-button>
            <el-button
              v-if="!scope.row.is_local&&src==='crawl'"
              size="mini"
              type="warning"
              @click="handleDeleteImageFromWeb(scope.row)"
            >从网站删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <div v-if="action !== 'delete'" style="margin-bottom: 10px">
        <gallery
          style="display: inline"
          color="#1890ff"
          class="editor-upload-btn"
          @successCBK="imageSuccessCBK"
        />
        <editorImage
          style="display: inline"
          color="#32CD32"
          class="editor-upload-btn"
          @successCBK="imageSuccessCBK"
        />
      </div>

      <el-form :model="temp" label-position="left" label-width="80px">

        <el-form-item v-if="action !== 'delete'" label="url">
          <el-input v-model="temp.url" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="name">
          <el-input v-model="temp.name" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, ImageSync, SetMainImage } from '@/api/erp/crawlproductimage'

import qs from 'qs'
import editorImage from '@/components/Tinymce/components/EditorImage'
import gallery from '@/components/gallery'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crawlimage',
  components: { editorImage, gallery },
  props: {
    imageDialogVisible: {
      type: Boolean,
      default: false
    },
    isDialog: {
      type: Boolean,
      default: true
    },
    product_id: {
      type: Number,
      required: true,
      deep: true
    },
    source: {
      type: String,
      default: 'crawl'
    },
    titlename: {
      type: String,
      default: '产品图片管理'
    }
  },
  data() {
    return {
      data: [],
      listLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      temp: {
        url: '',
        name: '',
        product_id: ''
      },
      width: '',
      title: '',
      projects: [],
      innerDialogVisible: false,
      fileList: [],
      history: [],
      multipleSelection: []
    }
  },
  // props: ['imageDialogVisible', 'product_id', 'titlename'],
  watch: {
    imageDialogVisible(v) {
      this.dialogVisible = v
      if (v) {
        this.getList()
      }
    },
    product_id(v) {
      if (v) {
        this.getList()
      }
    }
  },
  created() {
    // this.handleFetchProjects()
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp.url = ''
      this.temp.name = ''
    },
    getList() {
      if (this.product_id <= 0) {
        return
      }
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        source: this.source,
        order_by: this.order_by,
        order_desc: this.order_desc,
        product_id: this.product_id
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    imageSuccessCBK(arr) {
      this.temp.url = arr[0].url
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      // 抛出事件
      this.$emit('handleSelectionChange', val)
    },
    handleAddImageToWeb(row) {
      ImageSync({
        image_id: row.id,
        product_id: this.product_id,
        source: this.source,
        operate: 'add'

      }
      ).then(response => {
        this.getList()
        this.notify('同步成功')
      })
    },
    handleDeleteImageFromWeb(row) {
      if (!confirm('确定要从网站删除图片?')) {
        return
      }

      ImageSync({
        image_id: row.id,
        source: this.source,
        product_id: this.product_id,
        operate: 'delete'

      }
      ).then(response => {
        this.getList()
        this.notify('同步成功')
      })
    },
    handleSetMainImage(row) {
      this.listLoading = true
      SetMainImage({
        image_id: row.id,
        source: this.source,
        product_id: this.product_id

      }
      ).then(response => {
        this.getList()
        this.notify('同步成功')
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.url}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改图片${row.url}`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      _data.product_id = this.product_id
      switch (this.action) {
        case 'create':
          if (_data.product_id === '') {
            alert('必须选择产品')
            return
          }
          if (!_data.url.length) {
            alert('必须填写url')
            return
          }
          Post({
            url: _data.url,
            name: _data.name,
            product_id: _data.product_id,
            source: this.source

          }
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id,
            {
              url: _data.url,
              name: _data.name,
              source: this.source
            }).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, {
            url: _data.url,
            name: _data.name,
            source: this.source
          }).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleUploadSuccess(res) {
      // 如果上传成功 记录历史，用于 刷新 父控件
      if (res.success) {
        this.history.push(1)
        this.temp.url = res.data.url
        this.notify(res.data.name + '上传成功')
      } else {
        this.$notify({
          title: '失败',
          message: res.msg,
          type: 'error',
          duration: 8000
        })
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeDialog', false)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin: 168px auto !important;
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
  }
</style>
